from google.appengine.ext import db
from google.appengine.api import users

from google.appengine.api import urlfetch
import urllib

from datetime import datetime

import re

import base64


__PlurkURL__ = 'http://www.plurk.com'
__LoginURL__ = '/Users/login'
__PostURL__ = '/TimeLine/addPlurk'

__PlurkHTTPHeaders__ = {
                        'Connection': 'keep-alive',
                        'Keep-Alive': '300',
                        'Content-Type': 'application/x-www-form-urlencoded',
                        }

__UserIDRegex__ = 'showFriendsBasic\?user_id=([\d]*)'


__passwordPrefix__ = '__pass__='


class Plurker(db.Model):
    user = db.UserProperty(required=True)
    mobile_no = db.StringProperty(required=True)
    nickname = db.StringProperty(required=True)
    password = db.StringProperty(default='')
    uid = db.IntegerProperty()
    autokarma_enabled = db.BooleanProperty(default=False)
    autokarma_allowed = db.BooleanProperty(default=False)

    def setPassword(self, str):
        self.password = base64.b64encode(__passwordPrefix__ + str)

    def getPassword(self):
        if isEncodedPassword(self.password):
            password = base64.b64decode(self.password)
            return password[( password.find(__passwordPrefix__) + len(__passwordPrefix__) ):]
        else:
            return self.password

class Message(db.Model):
    plurker = db.ReferenceProperty(reference_class=Plurker,required=True)
    qualifier = db.StringProperty(default='')
    content = db.StringProperty(required=True)
    lang = db.StringProperty(default='en')


def post(message):
    if not message:
        return False

    plurker = message.plurker
    if not plurker:
        return False
    else:
        login_fields = {
          'nick_name': plurker.nickname,
          'password': plurker.getPassword()
        }
        login_data = urllib.urlencode(login_fields)
        login_result = urlfetch.fetch(url=__PlurkURL__+__LoginURL__,
                                      payload=login_data,
                                      method=urlfetch.POST,
                                      headers=__PlurkHTTPHeaders__,
                                      follow_redirects=False)

        login_cookie = login_result.headers.get('set-cookie')
        http_headers = __PlurkHTTPHeaders__.copy()
        http_headers['Cookie'] = login_cookie

        redirect_url = login_result.headers.get('location')
        if redirect_url.count("incorrect_login") == 0:
            redirect_result = urlfetch.fetch(url=redirect_url, method=urlfetch.GET)

            user_id = plurker.uid
            if not user_id:
                matcher = re.search(__UserIDRegex__, redirect_result.content)
                if matcher:
                    user_id = matcher.group(1)
                    plurker.uid = int(user_id)
                    plurker.put()

            if user_id:
                post_fields = {
                  'content': message.content,
                  'lang': message.lang,
                  'no_comments': '0',
                  'posted': datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                  'qualifier': message.qualifier,
                  'uid': str(user_id)
                }
                post_data = urllib.urlencode(post_fields)
                post_result = urlfetch.fetch(url=__PlurkURL__+__PostURL__,
                                              payload=post_data,
                                              method=urlfetch.POST,
                                              headers=http_headers,
                                              follow_redirects=False)
                return (post_result.status_code == 200)

    return False


def isEncodedPassword(str):
    test = str
    try:
        test = base64.b64decode(test)
    except TypeError:
        pass
    return test.startswith(__passwordPrefix__)
